<template>
  <div class="order-page">
    <!-- 商品信息展示 -->
    <div class="product-info" v-if="product">
      <van-image :src="product.picture" width="80" height="80" />
      <div class="details">
        <div class="name">{{ product.name }}</div>
        <div class="price">¥{{ product.price }}</div>
      </div>
    </div>

    <van-cell-group inset>
      <!-- 上传图文 -->
      <van-field label="上传文件" readonly>
        <template #button>
          <van-uploader
            :after-read="onAfterRead"
            :max-count="5"
            multiple
            accept="image/*"
          />
        </template>
      </van-field>

      <!-- 数量选择 -->
      <van-field label="数量" readonly>
        <template #button>
          <van-stepper v-model="form.quantity" min="1" />
        </template>
      </van-field>

      <!-- 移除手机号和验证码 -->

      <!-- 备注 -->
      <van-field
        v-model="form.remark"
        type="textarea"
        label="备注"
        placeholder="可填写特殊要求"
      />
    </van-cell-group>

    <!-- 提交订单按钮 -->
    <div class="submit-button" style="margin-top: 24px;">
      <van-button round block type="danger" @click="submitOrder">
        提交订单
      </van-button>
    </div>

    <!-- 加入购物车按钮 -->
    <div class="cart-button" style="margin-top: 12px;">
      <van-button round block type="info" @click="addToCart">
        加入购物车
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const productId = route.params.productId

const product = ref({
  id: productId,
  name: '商品名称',
  price: 0,
  picture: ''
})

const form = reactive({
  files: [],
  quantity: 1,
  remark: ''
})

function onAfterRead(file) {
  form.files.push(file)
}

function checkLogin() {
  const token = localStorage.getItem('token')
  return !!token
}

function sendSmsCode() {
  // 已移除手机号和验证码，这个函数可以删掉
}

function submitOrder() {
  if (!checkLogin()) {
    router.push('/login')
    return
  }
  console.log('submit order', form)
  router.back()
}

function addToCart() {
  if (!checkLogin()) {
    router.push('/login')
    return
  }
  const cart = JSON.parse(localStorage.getItem('cart') || '[]')
  const existingIndex = cart.findIndex(item => item.id === product.value.id)
  if (existingIndex > -1) {
    cart[existingIndex].quantity += form.quantity
  } else {
    cart.push({
      id: product.value.id,
      name: product.value.name,
      price: product.value.price,
      quantity: form.quantity,
      picture: product.value.picture
    })
  }
  localStorage.setItem('cart', JSON.stringify(cart))
  alert('已加入购物车')
}

onMounted(() => {
  if (!checkLogin()) {
    router.push('/login')
    return
  }
  // TODO: 获取商品信息
})
</script>
